/**
 * 权限激活接口
 */

//引入Q模块
let Q = require('q');

//引入公共函数
let util = require('../../util');

var mongo = require('mongodb');

let db, config, commonDB;

//activation入口函数
let index = function(getData, postData, _config, redis, _db) {
	let deferred = Q.defer();
	if(postData.loginCode && postData.registerCode && postData.registerCode.length == 6) {
		db = _db;
		config = _config;
		//发送GET请求到微信服务器请求sessionKey和用户数据
		util.get('https://api.weixin.qq.com/sns/jscode2session', {
			//小程序appid
			appid: config.serviceAppId,
			//小程序appSecret密钥
			secret: config.serviceAppSecret,
			//登录code
			js_code: postData.loginCode,
			//登录类型
			grant_type: config.grantType
		}).then(function(data) {
			console.log('激活权限接口获得用户ID：' + data.openid);
			if(!data.openid) {
				//权限激活获取用户ID失败
				deferred.reject('-0147');
			}
			else {
				let serviceId = data.openid;
				redis.get('registerCode-' + postData.registerCode).then(function(serviceData) {
					if(!serviceData) {
						//权限激活激活码无效
						deferred.reject('-0149');
					}
					else {
						let {storeId, storeName, serviceName, serviceAuth} = JSON.parse(serviceData);
						console.log(storeId, storeName, serviceName, serviceAuth);
						if(storeId || storeName) {
							let newDB;
							createStoreId(storeId).then(function(_storeId) {
								storeId = _storeId
								return createStore(storeId, storeName);
							}, function(errCode) {
								deferred.reject(errCode);
							}).then(function(_newDB) {
								newDB = _newDB;
								return newDB.select('allowServices', {id: serviceId});
							}, function(errCode) {
								//激活管理建立商户失败
								deferred.reject(errCode);
							}).then(function(allowServices) {
								if(allowServices.length == 0) {
									return newDB.insert('allowServices', {
										id: serviceId,
										name: serviceName || '管理员',
										auth: serviceAuth || 'admin',
										tableNums: '*'
									});
								}
								else {
									return newDB.update('allowServices', {
										id: serviceId
									}, {
										name: serviceName || storeName + '管理',
										auth: ((allowServices[0].auth == 'admin' && serviceAuth != 'admin') ? 'admin' : (serviceAuth || 'admin'))
									});
								}
							}, function(err) {
								console.log(err);
								//权限激活查找允许的管理失败
								deferred.reject('-0150');
							}).then(function() {
								return redis.expire('registerCode-' + postData.registerCode, 0);
							}, function() {
								//权限激活新增管理操作失败
								deferred.reject('-0151');
							}).then(function() {
								//权限激活成功返回信息
								deferred.resolve({
									storeId: storeId,
									storeName: storeName
								});
							}, function() {
								//删除已使用激活码失败
								deferred.reject('-0159');
							});
						}
						else {
							//权限激活激活码无效
							deferred.reject('-0149');
						}
					}
				}, function() {
					//权限激活获取激活码信息失败
					deferred.reject('-0148');
				});
			}
		}, function() {
			//权限激活获取用户ID失败
			deferred.reject('-0147');
		});
	}
	else {
		//权限激活参数错误
		deferred.reject('-0146');
	}
	return deferred.promise;
}

let createStoreId = function(storeId) {
	let deferred = Q.defer();
	if(storeId) {
		db.connectDB('common').then(function(_commonDB) {
			commonDB = _commonDB;
			deferred.resolve(storeId);
		}, function() {
			//生成随机字符串失败
			deferred.reject('-0069');
		});
	}
	else {
		util.createRandomStr(7).then(function(_storeId) {
			storeId = _storeId;
			return db.connectDB('common');
		}, function() {
			//生成随机字符串失败
			deferred.reject('-0069');
		}).then(function(_commonDB) {
			commonDB = _commonDB;
			return commonDB.select('storeList', {storeId: storeId});
		}, function() {
			deferred.reject('-0127');
		}).then(function(storeList) {
			if(storeList.length > 0) {
				util.createRandomStr(7).then(function(storeId) {
					deferred.resolve(storeId);
				}, function() {
					//生成随机字符串失败
					deferred.reject('-0069');
				});
			}
			else {
				deferred.resolve(storeId);
			}
		}, function() {
			deferred.reject('-0040');
		});
	}
	return deferred.promise;
}

let createStore = function(storeId, storeName) {
	let deferred = Q.defer();
	commonDB.select('storeList', {storeId: storeId}).then(function(storeData) {
		console.log(storeData);
		if(storeData.length > 0) {
			db.connectDB(storeId).then(function(_db) {
				deferred.resolve(_db);
			}, function() {
				//连接到商户数据库失败
				deferred.reject('-0154');
			});
		}
		else {
			let newDb;
			createFolder(storeId).then(function() {
				return createDB(storeId);
			}, function() {
				deferred.reject();
			}).then(function(_db) {
				newDb = _db;
				return newDb.insert('storeInfo', [
					{storeId: storeId},
					{storeName: storeName},
					{storeAdress: '暂无地址'},
					{storePhone: '暂无电话'},
					{storeDescription: '商户暂无简介'},
					{storeWecome: '客官您好！请问需要什么服务吗？'},
					{storeServiceOffLineMsg: '您好！本店服务员暂未在线，您的消息我们将在上线后转达服务员'},
					{storeBankCardInfo: {
						bankCardRealName: '',
						bankCardNumber: ''
					}}
				]);
			}, function() {
				//创建商户数据库失败
				deferred.reject('-0153');
			}).then(function() {
				return newDb.insert('foodTypes', [
					{typeName: 'dinner', typeVal: '主餐'},
					{typeName: 'snak', typeVal: '小吃'},
					{typeName: 'soup', typeVal: '汤类'},
					{typeName: 'drinks', typeVal: '酒水'}
				]);
			}, function() {
				//插入商户信息到商户数据库失败
				deferred.reject('-0156');
			}).then(function() {
				return commonDB.insert('storeList', {
					storeId: storeId,
					storeName: storeName,
					storeAdress: '暂无地址',
					storePhone: '暂无电话',
					storeStar: 5
				});
			}, function() {
				//插入菜品类型到商户数据库失败
				deferred.reject('-0157');
			}).then(function() {
				deferred.resolve(newDb);
			}, function() {
				//往公共数据库中插入新商户失败
				deferred.reject('-0154');
			});
		}
	}, function() {
		deferred.reject();
	});
	return deferred.promise;
}

let createFolder = function(storeId) {
	let deferred = Q.defer();
	let storePath = config.uploadPath + '/' + storeId;
	console.log('建立商户上传文件夹', storePath);
	util.fsExists(storePath).then(function() {
		deferred.resolve();
	}, function() {
		util.fsMkdir(storePath).then(function() {
			return util.fsMkdir(storePath + '/foodImage');
		}, function() {
			deferred.reject();
		}).then(function() {
			return util.fsMkdir(storePath + '/storeImage');
		}, function() {
			deferred.reject();
		}).then(function() {
			deferred.resolve();
		}, function() {
			deferred.reject();
		});
	});
	return deferred.promise;
}

let createDB = function(storeId) {
	let deferred = Q.defer();
	let newSrv = new mongo.Server('localhost', 8787, {auto_reconnect: true});
	let newDb = new mongo.Db(storeId, newSrv, {safe: true});
	newDb.open(function() {
		let adminDb = newDb.admin();
		adminDb.authenticate('Vinlic', 'cwb456289788', function(err) {
			if(err) {
				console.log(err);
				deferred.reject();
				return deferred.promise;
			}
			createTable(newDb, 'allowServices').then(function() {
				return createTable(newDb, 'attachGoods');
			}, function() {
				deferred.reject();
			}).then(function() {
				return createTable(newDb, 'autoReplyContents');
			}, function() {
				deferred.reject();
			}).then(function() {
				return createTable(newDb, 'chatListLogs');
			}, function() {
				deferred.reject();
			}).then(function() {
				return createTable(newDb, 'errorOrder');
			}, function() {
				deferred.reject();
			}).then(function() {
				return createTable(newDb, 'foodMenu');
			}, function() {
				deferred.reject();
			}).then(function() {
				return createTable(newDb, 'foodTypes');
			}, function() {
				deferred.reject();
			}).then(function() {
				return createTable(newDb, 'noReceiveFunLogs');
			}, function() {
				deferred.reject();
			}).then(function() {
				return createTable(newDb, 'storeFunInfo');
			}, function() {
				deferred.reject();
			}).then(function() {
				return createTable(newDb, 'storeInfo');
			}, function() {
				deferred.reject();
			}).then(function() {
				return createTable(newDb, 'storeOrder');
			}, function() {
				deferred.reject();
			}).then(function() {
				newDb.close();
				db.connectDB(storeId).then(function(_db) {
					deferred.resolve(_db);
				}, function(err) {
					console.log(err);
					deferred.reject();
				});
			}, function() {
				deferred.reject();
			});
		});
	});
	return deferred.promise;
}

let createTable = function(newDb, table) {
	let deferred = Q.defer();
	newDb.createCollection(table, {}, function(err, collection) {
		if(err) {
			console.log(err);
			deferred.reject();
		}
		else {
			deferred.resolve(collection);
		}
	});
	return deferred.promise;
}

module.exports = {
	index: index
};